package com.wzy.new_energy_car_platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wzy.new_energy_car_platform.common.GlobalVariable;
import com.wzy.new_energy_car_platform.common.ResultDto;
import com.wzy.new_energy_car_platform.dao.PostMapper;
import com.wzy.new_energy_car_platform.dao.SysUserMapper;
import com.wzy.new_energy_car_platform.model.Post;
import com.wzy.new_energy_car_platform.model.SysUser;
import com.wzy.new_energy_car_platform.service.PostService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzy.new_energy_car_platform.utils.JwtUtils;
import javafx.geometry.Pos;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 帖子 服务实现类
 * </p>
 *
 * @author wzy
 * @since 2024-04-10
 */
@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService {
    @Autowired
    private PostMapper postMapper;

    @Autowired
    private SysUserMapper sysUserMapper;
    @Override
    public ResultDto<?> getPost() {
        LambdaQueryWrapper<Post> postLambdaQueryWrapper = new LambdaQueryWrapper<>();
        postLambdaQueryWrapper.eq(Post::getValidFlag, GlobalVariable.VALID_TRUE)
                .orderByDesc(Post::getCreateTime);
        List<Post> posts = postMapper.selectList(postLambdaQueryWrapper);
        List<Map> result = new ArrayList<>();
        for (Post post : posts) {
            Long userId = post.getUserId();
            SysUser sysUser = sysUserMapper.selectById(userId);
            String[] split = post.getImg().split(",");
            for (int i = 0; i < split.length; i++) {
                split[i] = split[i] + ".jpg";
            }
            Map map = new HashMap();
            map.put("id",post.getId());
            map.put("userId",userId);
            map.put("userName",sysUser.getUserName());
            map.put("content",post.getContent());
            map.put("header",sysUser.getImg());
            map.put("img",split);

            result.add(map);
        }

        return ResultDto.ok(result);
    }

    @Override
    public ResultDto<?> submitPost(String token, String content) {
        // 获取用户id

        Map<String,Object> user = JwtUtils.getUser(token);
        if (Objects.isNull(user)){
            return ResultDto.error("手机号或密码错误！");
        }
        LambdaQueryWrapper<SysUser> sysUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysUserLambdaQueryWrapper.eq(SysUser::getPhoneNumber,user.get("phoneNumber"))
                .eq(SysUser::getPassword,user.get("password"))
                .eq(SysUser::getValidFlag, GlobalVariable.VALID_TRUE);

        SysUser sysUser = sysUserMapper.selectOne(sysUserLambdaQueryWrapper);

        //提取出content中 imgName=后 .jpg前的字符串

        String regexImg = "imgName=([^.]+).jpg";
        Pattern pattern = Pattern.compile(regexImg);
        Matcher matcher = pattern.matcher(content);
        List<String> imgList = new ArrayList<>();
        while (matcher.find()) {
            imgList.add(matcher.group(1));
        }
        String imgName = String.join(",", imgList);


        //正则表达式将content中 <img开头 >结尾的所有字符提取出来
        String regex = "<img.*?>";
        content = content.replaceAll(regex, "");
        // 正则表达式 去除content中所有 <p>
        String regex2 = "<p.*?>";
        content = content.replaceAll(regex2, "");
        //正则表达式  替换content所有的</p>为<br>
        String regex3 = "</p>";
        content = content.replaceAll(regex3, "<br>");


        // 创建帖子对象
        Post post = new Post();
        post.setUserId(sysUser.getId());
        post.setContent(content);
        post.setValidFlag(GlobalVariable.VALID_TRUE);
        post.setImg(imgName);
        // 调用mapper插入数据
        postMapper.insert(post);
        return ResultDto.ok();
    }

    @Override
    public ResultDto<?> uploadImg(MultipartFile image) {
        //将image上传到本地磁盘中
        String fileName = image.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString().replaceAll("-","") + suffixName;
        try {
            image.transferTo(new File("D:\\new_energy_car_platform\\new_energy_car_platform_web\\src\\imgs\\posting\\" + newFileName));

            } catch (IOException e) {
            e.printStackTrace();
            return ResultDto.error("上传失败");
        }
        Map map = new HashMap();

        map.put("imgName",newFileName);
        return ResultDto.ok("上传成功",map);
    }

    @Override
    public byte[] getImg(String imgName) {
        //根据imgName在D:\new_energy_car_platform\new_energy_car_platform_web\src\imgs\posting\中获取图片
        File file = new File("D:\\new_energy_car_platform\\new_energy_car_platform_web\\src\\imgs\\posting\\" + imgName);
        if(file.exists()){
            try {
                return FileCopyUtils.copyToByteArray(file);
            }
            catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }else {
            return null;
        }
    }

}
